package start.demo01.fileIO;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.binary.Base64;
import org.junit.Test;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class IMG2Base64 {


    private static final String PRE="data:image/jpeg;base64,";
    @Test
    public void t0() {
        String path = "C:\\Users\\wangcj\\Pictures\\联想锁屏壁纸\\8566935.jpg";
        try (InputStream in = new FileInputStream(path)) {
            byte[] bytes = in.readAllBytes();
            System.out.println("文件长度:" + bytes.length);
            String base64String = Base64.encodeBase64String(bytes);
            System.out.println(base64String);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String out2Str(ByteArrayOutputStream outputStream){
        byte[] bytes = outputStream.toByteArray();
        String base64String = Base64.encodeBase64String(bytes);
        return base64String;
    }

    @Test
    public void t2() throws InterruptedException, IOException {//图片编辑
        String path = "C:\\Users\\wangcj\\Pictures\\QQ浏览器截图\\t1.png";
        ByteArrayOutputStream out=new ByteArrayOutputStream();
        Thumbnails.of(path).size(100, 100).keepAspectRatio(false).toOutputStream(out);
        String str = out2Str(out);
        System.out.println("base64长度:"+str.length());
        System.out.println(PRE+str);
    }
    @Test//生成二维码
    public void generateQRCodeImage() throws WriterException, IOException {
        int width=350, height=350;
        String  text="phone:18982639219";
        ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        // 解决中文乱码的关键：设置字符编码为UTF-8，微信不支持中文内容
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 设置纠错级别
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        String overlayText = "挪车联系我";

        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
//        MatrixToImageWriter.writeToStream(bitMatrix, "PNG",outputStream);
        BufferedImage bufferedImage = addTextToImage(MatrixToImageWriter.toBufferedImage(bitMatrix), overlayText, width, height);
        ImageIO.write(bufferedImage, "PNG", outputStream);
        System.out.println(PRE+out2Str(outputStream));
    }
    @Test//解析二维码
    public void anaRQCode() throws Exception {
        InputStream is = new FileInputStream("C:\\Users\\wangcj\\Pictures\\QQ浏览器截图\\i1.png");
        BufferedImage image = ImageIO.read(is);
        LuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bb = new BinaryBitmap(new HybridBinarizer(source));
        HashMap<DecodeHintType, String> hints = new HashMap<>();
        hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
        Result result =
                new MultiFormatReader().decode(bb, hints);
        System.out.println("二维码格式类型：" + result.getBarcodeFormat());
        System.out.println("二维码文本内容：" + result.getText());
    }


    /**
     * 在图片下方添加文字
     */
    private static BufferedImage addTextToImage(BufferedImage image, String text, int width, int height) {
        // 创建一个新的图片，高度增加50像素用于显示文字
        BufferedImage combined = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = combined.createGraphics();

        // 设置背景为白色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);

        // 绘制二维码
        g.drawImage(image, 0, 0, null);
        // 设置字体和颜色
        g.setColor(Color.pink);
        g.setFont(new Font("SimHei", Font.PLAIN, 16));

        // 计算文字居中位置
        FontMetrics metrics = g.getFontMetrics();
        int textWidth = metrics.stringWidth(text);
        int textX = (width - textWidth) / 2;
        int textY = height - 20;

        // 绘制文字
        g.drawString(text, textX, textY);
        g.dispose();

        return combined;
    }
}